package com.fancy.mobileschool.ui;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.fancy.mobileschool.MyConfiguration;
import com.fancy.mobileschool.R;
import com.fancy.mobileschool.entity.GroupChatMessage;
import com.fancy.mobileschool.service.ChatGroupService;
import com.fancy.mobileschool.task.TaskExecutor;
import com.fancy.mobileschool.ui.adapt.ChatGroupMessageAdapter;

import java.util.ArrayList;
import java.util.List;

public class ChatGroupRoomActivity extends AppCompatActivity implements View.OnClickListener{

    private final static int REFRESH_MESSAGES = 1;

    private final static int SEND_MESSAGE_OK = 2;

    private final static int SEND_MESSAGE_FAIL = 3;

    private String course_id;

    private ChatGroupService chatGroupService;

    private RecyclerView recyclerView;

    private ChatGroupMessageAdapter adapter;

    private EditText editText;

    private Button sendButton;

    private List<GroupChatMessage> messages = new ArrayList<>();

    private volatile boolean run = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_room);
        chatGroupService = new ChatGroupService();
        course_id = getIntent().getStringExtra("course_id");
        recyclerView = (RecyclerView) findViewById(R.id.chat_room_message_recycleview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ChatGroupMessageAdapter(ChatGroupRoomActivity.this, messages);
        recyclerView.setAdapter(adapter);

        sendButton = (Button) findViewById(R.id.send_button);
        editText = (EditText) findViewById(R.id.input);

        sendButton.setOnClickListener(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        run = true;
        refreshConversation();
    }

    @Override
    protected void onPause() {
        super.onPause();
        run = false;
    }

    private void refreshConversation() {
        TaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                while (run){
                    List<GroupChatMessage> latestMessages = chatGroupService.getGroupConversation(course_id);
                    if (latestMessages != null) {
                        messages = latestMessages;
                        handler.sendEmptyMessage(REFRESH_MESSAGES);
                    }

                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == REFRESH_MESSAGES) {
                adapter.putDate(messages);
                adapter.notifyDataSetChanged();
            }else if (msg.what == SEND_MESSAGE_OK) {
                adapter.notifyDataSetChanged();
                recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
                editText.setText("");
            }else if (msg.what == SEND_MESSAGE_FAIL) {
                Toast.makeText(ChatGroupRoomActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.send_button) {
            String content = editText.getText().toString();
            sendMessage(new GroupChatMessage(MyConfiguration.myID, course_id, null, content, MyConfiguration.myName));
        }
    }

    private void sendMessage(final GroupChatMessage message) {
        TaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                boolean result = false;
                if (message.content != null) {
                    result = chatGroupService.sendGroupMessage(message);
                }

                if (result) {
                    adapter.addDate(message);
                    handler.sendEmptyMessage(SEND_MESSAGE_OK);
                }else
                    handler.sendEmptyMessage(SEND_MESSAGE_FAIL);

            }
        });


    }
}
